package com.bidding.auth.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.img.ImgUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bidding.auth.mapper.AuthMapper;
import com.bidding.auth.pojo.dto.LoginDTO;
import com.bidding.auth.pojo.entity.AuthUser;
import com.bidding.auth.pojo.vo.AuthCaptchaVO;
import com.bidding.auth.service.AuthService;
import com.bidding.common.utils.RedisUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Locale;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class AuthServiceImpl extends ServiceImpl<AuthMapper, AuthUser> implements AuthService {

    private static final String chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    @Resource
    private RedisUtil redisUtil;

    @Override
    public AuthCaptchaVO captcha() {
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(200, 100, 6, 30);
        captcha.setGenerator(new RandomGenerator(chars, 6));
        captcha.createCode();

        String captchaCode = captcha.getCode();
        BufferedImage image = captcha.getImage();

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImgUtil.writePng(image, os);
        String imageBase64 = "data:image/png;base64," + Base64.encode(os.toByteArray());

        // 生成唯一标识用于后续验证
        String captchaId = UUID.randomUUID().toString();

        //设置code忽略大小写
        captchaCode = captchaCode.toLowerCase(Locale.ROOT);
        redisUtil.setNx(captchaId,captchaCode, 60L, TimeUnit.SECONDS);
        //返回数据
        AuthCaptchaVO authCaptchaVO = new AuthCaptchaVO();
        authCaptchaVO.setUuid(captchaId);
        authCaptchaVO.setBase64Img(imageBase64);
        return authCaptchaVO;
    }

    @Override
    public SaTokenInfo login(LoginDTO loginDTO) {
        return null;
    }
}
